import React, { useState, useMemo } from 'react';
import { TableData } from '../../KimiChat';
import './DataTable.scss';

interface DataTableProps {
    data: TableData[];
    sessionTitle?: string;
}

type SortField = keyof TableData;
type SortDirection = 'asc' | 'desc';

interface SortConfig {
    field: SortField;
    direction: SortDirection;
}

const DataTable: React.FC<DataTableProps> = ({ data, sessionTitle }) => {
    const [sortConfig, setSortConfig] = useState<SortConfig | null>(null);
    const [filterCategory, setFilterCategory] = useState<string>('all');
    const [filterStatus, setFilterStatus] = useState<string>('all');
    const [searchTerm, setSearchTerm] = useState<string>('');

    // 获取所有唯一的类别和状态
    const categories = useMemo(() => {
        const categorySet = new Set(data.map(item => item.category));
        return Array.from(categorySet);
    }, [data]);

    const statuses = useMemo(() => {
        const statusSet = new Set(data.map(item => item.status));
        return Array.from(statusSet);
    }, [data]);

    // 过滤和排序数据
    const processedData = useMemo(() => {
        let filtered = data.filter(item => {
            const matchesCategory = filterCategory === 'all' || item.category === filterCategory;
            const matchesStatus = filterStatus === 'all' || item.status === filterStatus;
            const matchesSearch = searchTerm === '' || 
                item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                item.category.toLowerCase().includes(searchTerm.toLowerCase());
            
            return matchesCategory && matchesStatus && matchesSearch;
        });

        if (sortConfig) {
            filtered.sort((a, b) => {
                const aValue = a[sortConfig.field];
                const bValue = b[sortConfig.field];
                
                if (typeof aValue === 'number' && typeof bValue === 'number') {
                    return sortConfig.direction === 'asc' ? aValue - bValue : bValue - aValue;
                }
                
                const aStr = String(aValue).toLowerCase();
                const bStr = String(bValue).toLowerCase();
                
                if (sortConfig.direction === 'asc') {
                    return aStr.localeCompare(bStr);
                } else {
                    return bStr.localeCompare(aStr);
                }
            });
        }

        return filtered;
    }, [data, sortConfig, filterCategory, filterStatus, searchTerm]);

    const handleSort = (field: SortField) => {
        setSortConfig(prevConfig => {
            if (prevConfig?.field === field) {
                if (prevConfig.direction === 'asc') {
                    return { field, direction: 'desc' };
                } else {
                    return null; // 取消排序
                }
            } else {
                return { field, direction: 'asc' };
            }
        });
    };

    const getSortIcon = (field: SortField) => {
        if (sortConfig?.field !== field) {
            return '↕️';
        }
        return sortConfig.direction === 'asc' ? '↑' : '↓';
    };

    const getStatusColor = (status: string) => {
        switch (status) {
            case '正常':
                return 'success';
            case '异常':
                return 'error';
            case '警告':
                return 'warning';
            default:
                return 'default';
        }
    };

    if (!sessionTitle) {
        return (
            <div className="data-table">
                <div className="data-table__header">
                    <h3 className="data-table__title">{sessionTitle} - 数据分析结果</h3>
                </div>
                <div className="data-table__empty">
                    <div className="data-table__empty-icon">📊</div>
                    <p>请选择一个对话</p>
                    <p className="data-table__empty-tip">选择左侧对话后，分析结果将在这里显示</p>
                </div>
            </div>
        );
    }
    
    if (data.length === 0) {
        return (
            <div className="data-table">
                <div className="data-table__header">
                    <h3 className="data-table__title">{sessionTitle} - 数据分析结果</h3>
                </div>
                <div className="data-table__empty">
                    <div className="data-table__empty-icon">📊</div>
                    <p>暂无数据</p>
                    <p className="data-table__empty-tip">发送消息后，分析结果将在这里显示</p>
                </div>
            </div>
        );
    }

    return (
        <div className="data-table">
            <div className="data-table__header">
                <h3 className="data-table__title">数据分析结果</h3>
                <div className="data-table__count">
                    共 {processedData.length} 条数据
                </div>
            </div>
            
            <div className="data-table__filters">
                <div className="data-table__search">
                    <input
                        type="text"
                        placeholder="搜索数据..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="data-table__search-input"
                    />
                </div>
                
                <div className="data-table__filter-row">
                    <select
                        value={filterCategory}
                        onChange={(e) => setFilterCategory(e.target.value)}
                        className="data-table__filter-select"
                    >
                        <option value="all">所有类别</option>
                        {categories.map(category => (
                            <option key={category} value={category}>{category}</option>
                        ))}
                    </select>
                    
                    <select
                        value={filterStatus}
                        onChange={(e) => setFilterStatus(e.target.value)}
                        className="data-table__filter-select"
                    >
                        <option value="all">所有状态</option>
                        {statuses.map(status => (
                            <option key={status} value={status}>{status}</option>
                        ))}
                    </select>
                </div>
            </div>
            
            <div className="data-table__content">
                <table className="data-table__table">
                    <thead>
                        <tr>
                            <th 
                                className="data-table__th data-table__th--sortable"
                                onClick={() => handleSort('name')}
                            >
                                名称 <span className="data-table__sort-icon">{getSortIcon('name')}</span>
                            </th>
                            <th 
                                className="data-table__th data-table__th--sortable"
                                onClick={() => handleSort('value')}
                            >
                                数值 <span className="data-table__sort-icon">{getSortIcon('value')}</span>
                            </th>
                            <th 
                                className="data-table__th data-table__th--sortable"
                                onClick={() => handleSort('category')}
                            >
                                类别 <span className="data-table__sort-icon">{getSortIcon('category')}</span>
                            </th>
                            <th 
                                className="data-table__th data-table__th--sortable"
                                onClick={() => handleSort('status')}
                            >
                                状态 <span className="data-table__sort-icon">{getSortIcon('status')}</span>
                            </th>
                            <th 
                                className="data-table__th data-table__th--sortable"
                                onClick={() => handleSort('date')}
                            >
                                日期 <span className="data-table__sort-icon">{getSortIcon('date')}</span>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        {processedData.map(item => (
                            <tr key={item.id} className="data-table__row">
                                <td className="data-table__td data-table__td--name">
                                    {item.name}
                                </td>
                                <td className="data-table__td data-table__td--value">
                                    {item.value.toLocaleString()}
                                </td>
                                <td className="data-table__td">
                                    <span className="data-table__category">
                                        {item.category}
                                    </span>
                                </td>
                                <td className="data-table__td">
                                    <span className={`data-table__status data-table__status--${getStatusColor(item.status)}`}>
                                        {item.status}
                                    </span>
                                </td>
                                <td className="data-table__td data-table__td--date">
                                    {item.date}
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
};

export default DataTable;